package com.剑指offer;

import java.util.*;

public class HashMap排序
{
    public static void main(String[] args)
    {
        HashMap<Integer, User> map = new HashMap<>();
        map.put(1, new User("mazhao", 22));
        map.put(2, new User("zhangchuan", 24));
        map.put(3, new User("weicaohai", 23));
        map.put(4, new User("weicaohai", 25));
        map.put(5, new User("weicaohai", 29));
        HashMap<Integer, User> integerUserHashMap = sortUser(map);
        System.out.println(integerUserHashMap);
    }

    public static HashMap<Integer, User> sortUser(HashMap<Integer, User> map)
    {
        Set<Map.Entry<Integer, User>> entries = map.entrySet();
        List<Map.Entry<Integer, User>> list = new ArrayList<>(entries);
        Collections.sort(list, new Comparator<Map.Entry<Integer, User>>()
        {
            @Override
            public int compare(Map.Entry<Integer, User> o1, Map.Entry<Integer, User> o2)
            {
                return o1.getValue().getAge() - o2.getValue().getAge();
            }
        });
        LinkedHashMap<Integer,User> linkedHashMap = new LinkedHashMap<>();
        for(Map.Entry<Integer,User> entry : list){
            linkedHashMap.put(entry.getKey(),entry.getValue());
        }
        return linkedHashMap;
    }
}

class User
{
    private String name;
    private int age;

    public User(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    @Override
    public String toString()
    {
        return "User{" + "name='" + name + '\'' + ", age=" + age + '}';
    }
}
